﻿#include "todolistitemfragment.h"
#include "ui_todolistitemfragment.h"
#include "loader.h"
#include "todoshowitem.h"
#include "gettodoitem.h"
#include <QDebug>
TODOListItemFragment::TODOListItemFragment(TODOList list, QWidget *parent):QWidget(parent), ui(new Ui::TODOListItemFragment)
{
    ui->setupUi(this);
    this->list = list;
    ui->label_name->setText(list.getName());
    this->layout = new QGridLayout;
    for(auto x:list.getItems()){
        TODOShowItem *fragment = new TODOShowItem(x);
        fragment->setMinimumSize(QSize(fragment->geometry().width(),fragment->geometry().height()));
        layout->addWidget(fragment);
        connect(fragment,&TODOShowItem::textChange,this,&TODOListItemFragment::todoitemchange);
    }
    ui->scrollArea->widget()->setLayout(layout);
}

TODOListItemFragment::~TODOListItemFragment()
{
    delete ui;
}

bool TODOListItemFragment::isChosen()
{
    return this->ischosen;
}

void TODOListItemFragment::on_pushButton_add_clicked()
{
    TODOItem item = GetTODOItem::getTODOItem();
    this->list.addTODOItem(item);
    qDebug()<<"here";
    TODOShowItem *sitm = new TODOShowItem(item);

    this->layout->addWidget(sitm);
    QVector<TODOList> v;
    v.push_back(this->list);
    Loader::saveTODOList(v,QString("./savings/todolists/todolist%1.json").arg(list.getName()));
}

void TODOListItemFragment::on_pushButton_del_clicked()
{
    for(int i = 0;i<layout->count();i++){
        QLayoutItem* pLayout = layout->itemAt(i);
        TODOShowItem *frag = (TODOShowItem*)pLayout->widget();
        if(frag->isChosen()){
            frag->deleteLater();
        }
    }
    QVector<TODOList> v;
    v.push_back(this->list);
    Loader::saveTODOList(v,QString("./savings/todolists/todolist%1.json").arg(list.getName()));
}

void TODOListItemFragment::todoitemchange(QString name, QString exp)
{
    this->list.setItem(name,exp);
    QVector<TODOList> v;
    v.push_back(this->list);
    Loader::saveTODOList(v,QString("./savings/todolists/todolist%1.json").arg(list.getName()));
}

void TODOListItemFragment::on_checkBox_stateChanged(int arg1)
{
    this->ischosen = arg1;
}

TODOList TODOListItemFragment::getList()
{
    return this->list;
}
